package cn.sh.yhk.file.service.impl;

import cn.sh.yhk.base.utils.UUIDUtils;
import cn.sh.yhk.file.mapper.FileMapper;
import cn.sh.yhk.file.model.FilePo;
import cn.sh.yhk.file.service.FileService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @Classname Yhk
 * @Description TODO
 * @Version 1.0.0
 * @Date 2024/10/1 17:20
 * @Created by y6522
 */
@Service
@Slf4j
public class FileServiceImpl extends ServiceImpl<FileMapper, FilePo> implements FileService {

    @Autowired
    FileMapper fileMapper;

    //       private String uploadPath = "Y:\\西门茅王";
    @Value("${file.path}")
    private String uploadPath = "/imgfile/";

    @Override
    public int save(File file) {
        String fileName = file.getName();
        log.info("文件名:{}", fileName);
        FilePo filePo = new FilePo();
        LambdaQueryWrapper<FilePo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FilePo::getFileName, fileName);
        if (fileMapper.selectCount(queryWrapper) > 0) {
            String fileSuffix = fileName.substring(fileName.lastIndexOf("."));
            fileName = "tmp_" + UUIDUtils.getUUID() + fileSuffix;
            filePo.setFileName(fileName);
        } else {
            filePo.setFileName(fileName);
        }
        fileMapper.insert(filePo);
        return Math.max(0, filePo.getId());
    }

    @Override
    public File getFile(int id) {
        FilePo po = fileMapper.selectById(id);
        Path imagePath = Paths.get(uploadPath + po.getFileName());
        log.info("读取图片{}", imagePath.toString());
        return new File(imagePath.toString());
    }
}
